const sockets = new Set();
// 打开一个 web socket

// var ws = new WebSocket("ws://localhost:3001");

// ws.onopen = function () {
//     // Web Socket 已连接上，使用 send() 方法发送数据
//     var resuest = { RequestType: 1 }
//     ws.send(JSON.stringify(resuest));
// };

// ws.onmessage = function (evt) {
//     var received_msg = evt.data;
//     console.log(received_msg);
//     // sockets.forEach(r=>r.postMessage(received_msg));
// };

// ws.onclose = function () {
//     // 关闭 websocket
//     console.log("连接已关闭...");
//     // sockets.forEach(r=>r.postMessage("连接已关闭..."));
// };

// function sendMsg(value) {
//     ws.send(value);
// }

onconnect = function (e) {
    var port = e.ports[0];
    sockets.add(port);
    port.onmessage = function (e) {
        if (e.data === 0) sockets.delete(port);
        // setItem({key:'aaa',value:'bbbbbbbbbbbbbbbbb'});
        // self.sessionStorage.setItem("aa","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
        port.postMessage(sockets.size);
        // port.close();
    }
    port.onmessageerror=function (e) {
        console.log("error",e);
    }
};

setInterval(() => {
    sockets.forEach(p => {
        try {
            p.postMessage("ping");
            console.log("aaaa");
        } catch (error) {
            console.log(error);
        }

    })
}, 3000);